#include <algorithm>
#include "index.hpp"
#include "util.hpp"
#include <jsoncpp/json/json.h>
#include<map>
namespace ns_searcher
{
    struct InvertedElemPrint{
        uint64_t doc_id;
        int weight;
        std::vector<std::string>words;
        InvertedElemPrint():doc_id(0),weight(0){}
    };
    class Searcher
    {
    private:
        ns_index::Index *index;

    public:
        Searcher() {}
        ~Searcher() {}
        // 获取创建的index对象 并建立索引
        void InitSearcher(const std::string &input)
        {

            index = ns_index::Index::GetInstance();
            //std::cout << "创建单例" << std::endl;
            index->BuildIndex(input);
            //std::cout << "创建索引成功" << std::endl;
        }

        // 获取摘要
        std::string GetDesc(const std::string &content, std::string &word)
        {
            const int prev_step = 50;
            const int next_stop = 50;
            // 首次出现
            // std::size_t pos = content.find(word);
            // if (pos == std::string ::npos)
            // {
            //     return "None1";
            // }

            //大小写匹配
            auto iter = std::search(content.begin(),content.end(),word.begin(),word.end(),[](int x,int y){
                return (std::tolower(x) == std::tolower(y));
            });
            if(iter == content.end()){
                return "None1";
            }
            int pos = std::distance(content.begin(),iter);

            // 截取子串
            int start = 0;
            int end = content.size() - 1;
            if (pos > start + prev_step)
                start = pos - prev_step;
            if (pos < end - next_stop)
                end = pos + next_stop;

            if (start >= end)
                return "None2";
            return content.substr(start, end - start);
        }
        // query 用户输入的关键字
        // json_string 返回给用户的结果
        void Search(const std::string &query, std::string *json_string)
        {
            // 分词：对query进行分词
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            // 触发：根据分词，进行查找
            //ns_index::InvertedList inverted_list_all;
            std::vector<InvertedElemPrint>inverted_list_all;
            std::unordered_map<uint64_t,InvertedElemPrint>token_map;

            for (std::string word : words)
            {
                boost::to_lower(word);
                // 获取倒排拉链
                ns_index::InvertedList *inverted_list = index->GetInvertedList(word);
                if (nullptr == inverted_list)
                {
                    continue;
                }
                //inverted_list_all.insert(inverted_list_all.end(), inverted_list->begin(), inverted_list->end());
                //
                for(auto &elem : *inverted_list){

                    auto &item =  token_map[elem.doc_id];
                    //item一定是具有相同doc_id的结点
                    item.doc_id = elem.doc_id;
                    item.weight = elem.weight;
                    item.words.push_back(elem.word);
                }
            }
            for(auto &item : token_map){
                inverted_list_all.push_back(std::move(item.second));
            }
            // 汇总查找结果，按照相关性降序排序
            // operable program or batch file
            // std::sort(inverted_list_all.begin(), inverted_list_all.end(),
            //     [](const ns_index::InvertedElem &e1, const ns_index::InvertedElem &e2)
            // {
            //    return e1.weight > e2.weight;
            // });
            std::sort(inverted_list_all.begin(), inverted_list_all.end(),
                [](const InvertedElemPrint &e1, const InvertedElemPrint &e2)
            {
               return e1.weight > e2.weight;
            });
            // 构建json_string
            Json::Value root;
            for (auto &item : inverted_list_all)
            {
                // 查正排
                ns_index::DocInfo *doc = index->GetForwardIndex(item.doc_id);
                if (nullptr == doc)
                {
                    continue;
                }
                // 安装jsoncpp：sudo yum install -y jsoncpp-devel
                // Value Reader(反序列化) Writer(序列化)
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content, item.words[0]);
                elem["url"] = doc->url;
                //for debug
                elem["id"] = (int)item.doc_id;
                elem["weight"] = item.weight;
                
                root.append(elem);
            }
            Json::StyledWriter writer;
            *json_string = writer.write(root);
        }
    };
}